<template>
  <div class="page">
    <layout-card :filters="filterOptions" @search-change="searchChange" @search-reset="searchReset" headtitle="数据筛选">
        <template #action >
          <el-button type="primary" @click="exportData" :loading="exportLoading" :disabled="exportLoading">导出</el-button>
        </template>
        <table-common ref="tableRef1" :columns="columns" :loading="loading" :pagination="pager" :table-data="tableData"
            size="large" @current-change="currentChange" @size-change="sizeChange" style="margin-top: 12px;" @sort-change="sortChange">
            <template #eventStatus="{ row }">
              <span>{{ row ? dicFormatter(options.evenStatusOptions,row.eventStatus) : ''}}</span>
            </template>
            <!-- <template #eventHead="{ row }">
              <span>{{ row ? dicFormatter(userList,row.eventHead) : ''}}</span>
            </template> -->
            <template #eventTypeId="{ row }">
              <span>{{ row ? dicFormatter(options.eventTypeOptions,row.eventTypeId) : ''}}</span>
            </template>
            <template #action="{ row }">
              <el-button class="link-btn" link type="primary" @click="openDetailDialog(row)">查看</el-button>
              <el-button v-if="row.eventStatus===1" class="link-btn" link type="primary" @click="openUpdateDialog(row)">填报</el-button>
              <el-popconfirm title="确定要转知识库吗?" @confirm="() =>toKnow(row)">
                <template #reference>
                  <el-button v-if="row.eventStatus===2" class="link-btn" link type="primary">事件转知识库</el-button>
                </template>
              </el-popconfirm>
            </template>
        </table-common>
    </layout-card>
    <FillAndDetial ref="fillAndDetailRef" :options="options" @success="upDateList"/>
  </div>
</template>

<script lang="ts" setup>
import {
  PageListType,
  getPageList,
  exportList,
  toKnowledge
} from '@/api/event/record'
// import BreadCrumbRow from "@/components/BreadCrumbRow/index.vue"
import LayoutCard from '@/components/LayoutCard/index.vue'
import TableCommon from '@/components/TableCommon/index.vue'
import FillAndDetial from './components/FillAndDetail.vue'
import {getResource} from "@/api/resource";
import { ElMessage ,ElMessageBox, dayjs, rowProps} from 'element-plus'
import { ref,reactive,onBeforeMount} from 'vue'
import { filterOptions } from './config/filter'
import { columns } from './config/columns'
import dicFormatter from '@/hooks/commonUtil'
// import {getUserInfo} from "@/api/eqpt/houseManger";

interface Search {
  eventName?: string
  date?:string[]
  eventTypeIds?:number[]
}
interface OrderItem {
  column?: string
  method?: string
}
// const userList:any=ref([])
const fillAndDetailRef=ref();
const search = ref<Search>({}) // condition未格式化的值
const order = ref([] as OrderItem[])
const loading = ref(false)
const tableData:any = ref([])
const pager = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})
// options
const options = reactive({
  evenStatusOptions:[
    {
      value: 1,
      label: '处置中'
    },
    {
      value: 2,
      label: '已完结' // 已完结已转知识库
    },
    {
      value: 3,
      label: '已完结' // 已完结未转知识库
    }
  ],
  eventTypeOptions:[]
})
// 加载字典
function loadDict() {
  // getUserInfo({}).then((res:any)=>{
  //   userList.value=res.data.map((item:any)=>{
  //     return {
  //       value: item.userId,
  //       label: item.name
  //     }
  //   })
  // })
  Promise.all([
    getResource('event_common_type'), 
    // getResource('event_common_status'),
  ]).then(([
            res1,
            // res2,
          ]) => {
            filterOptions.value[2].inputProps.options = res1.data.properties.meta;
            options.eventTypeOptions = res1.data.properties.meta;
            // console.log(res2.data.properties.meta,'llllllll')
          })
}
/**
 * 点击重置
 * @param data 数据
 */
const tableRef1=ref();
const searchReset = (data: FilterDataType) => {
  search.value = data
  order.value = [] // 清空排序？？？
  tableRef1.value.clearSort()
  pager.currentPage = 1
  pager.pageSize = 10
  loadData()
}

const loadData = async() => {
  loading.value = true;
  const { eventName, eventTypeIds,date } =search.value
  const payload: PageListType = {
    pageNum: pager.currentPage,
    pageSize: pager.pageSize,
    condition: {
      eventName,
      eventTypeIds,
    },
    order:order.value.length? order.value:undefined
  }
  if(!date || date?.length === 0){
    payload.condition.occurTimeStart = undefined
    payload.condition.occurTimeEnd = undefined
  }else{
    payload.condition.occurTimeStart = date[0]
    payload.condition.occurTimeEnd = date[1]
  }
  getPageList(payload).then((res:any)=>{
    tableData.value = res.data.list
    pager.total = res.data.total
  }).catch((err: any) => {
    ElMessage.error(err?.message || '查询失败')
  }).finally(()=>{
    loading.value = false;
  })
}

// 分页
const sizeChange = (size: number) => {
  // 感觉这里要查第一页？？？？？
  pager.currentPage = 1
  pager.pageSize = size
  order.value = [] // 清空排序？？？
  loadData()
}
const currentChange = (value: number) => {
  pager.currentPage = value
  loadData()
}

/**
 * 点击查询
 */
const searchChange = (data: FilterDataType) => {
  // 这里也应该查第一页
  pager.currentPage = 1
  search.value = data
  loadData()
}
// 排序 
function sortChange(column:any){
  pager.currentPage = 1;
  const method = column.order==='descending'?'desc':'asc'
  order.value=[{ column: column.prop, method, }]
  loadData()
}

const exportLoading = ref(false);
const exportData = () => {
  exportLoading.value=true;
  const { eventName, eventTypeIds } =search.value
  const payload: any = {
    // pageNum: pager.currentPage,
    // pageSize: pager.pageSize,
    condition: {
      eventName,
      eventTypeIds
    },
    order:order.value.length? order.value:undefined
  }
  if(!search.value.date || search.value.date?.length === 0){
    payload.condition.occurTimeStart = undefined
    payload.condition.occurTimeEnd = undefined
  }else{
    payload.condition.occurTimeStart =search.value.date[0]
    payload.condition.occurTimeEnd = search.value.date[1]
  }
  exportList(payload)
    .then((res:any) => {
      const link = document.createElement('a')
      const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
      link.style.display = 'none'
      link.href = URL.createObjectURL(blob)
      link.setAttribute(
        'download',
        `普通事件记录${dayjs().format('YYYY-MM-DD')}.xlsx`
      )
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    })
    .catch((err: any) => {
      const reader = new FileReader();
      reader.readAsText(err,'utf-8');
      reader.onload=()=>{
        try{
          const json = JSON.parse(reader.result as string);
          ElMessage.error(json?.message || '导出失败')
        } catch(e){
      } 
      }
      
    })
    .finally(()=>{
      exportLoading.value=false;
    })
}
function upDateList(){
  pager.currentPage = 1
  loadData()
}
// 查看
function openDetailDialog (row:any){
  fillAndDetailRef.value.open('detail',row);
}
function openUpdateDialog (row:any){
  fillAndDetailRef.value.open('fill',row);
}
function toKnow(row:any) {
  toKnowledge(row.id).then((res:any)=>{
    ElMessage.success('操作成功')
    loadData();

  }).catch((err:any)=>{
    ElMessage.error(err?.message || '操作失败')
  })
}


const initData = () => {
  loadDict()
  loadData()
}

onBeforeMount(initData)
</script>
<style lang="less" scoped>
// .page{
  
// }
.card-box {
  padding: 24px;
  margin: 12px;
  background-color: #fff;
  border-radius: 8px;
}
.radio-group-task {
  margin-left: 24px;
}
.bread {
  padding: 20px 0 0 12px;
}
</style>
